package web.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import web.bo.*;
import web.common.CutPageBean;
import web.dao.EarthquakeReliefDao;
import web.dao.IndexDao;
import web.entity.IntegrationEntity;
import web.entity.StandardEntity;
import web.mapper.LogMysqlMapper;
import web.service.IndexService;
import web.utils.CommonConvertUtils;
import web.utils.PictureUtils;
import web.utils.VideoUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class IndexServiceImpl implements IndexService {
    @Resource(name = "kbaseIndex")
    private IndexDao indexDao;

    @Autowired
    private EarthquakeReliefDao earthquakeReliefDao;

    @Value("${filePath.CoverPic}")
    private String CoverPic;

    @Value("${filePath.VideoPath}")
    private String VideoPath;

    @Autowired
    LogMysqlMapper logMysqlMapper;

    @Override
    public List<StandardEntity> GetIndexData(String code, String top) {
        StandardEntityBo standardEntityBo = new StandardEntityBo(code, top);
        return indexDao.GetIndexData(standardEntityBo);
    }

    @Override
    public List<StandardEntity> GetPicture(String code, String top) {
        StandardEntityBo standardEntityBo = new StandardEntityBo(code, top);
        return indexDao.GetPicture(standardEntityBo);
    }

    @Override
    public List<VIdeoResourBo> GetVideo(VIdeoResourBo vIdeoResourBo) {
        List<VIdeoResourBo> list = earthquakeReliefDao.getVideo(vIdeoResourBo);
        for (VIdeoResourBo entityBo : list) {
            // 在生成截图。 并且把图片存在某个地方
            //这里进行截图反写
            if (entityBo.getPicAddress() == "" || entityBo.getPicAddress() == null) {
                try {
                    // 1. 先获取视频的地址
                    String path = VideoPath + entityBo.getFileName();
                    String s = VideoUtils.fetchFrame(path);
                    String suffix = "png";//图片文件的后缀名。可以是jpg、gif
                    String filePath = entityBo.getTitle() + "." + suffix;
                    String newFileName = CoverPic + filePath;//在Eclipse里面，生成的文件也在工程文件夹下
                    PictureUtils.base64StringToImage(s, newFileName, suffix);
//                        // 然后这里进行更新我们的哪条数据 进行反写
                    entityBo.setPicAddress(filePath);
                    Boolean b = earthquakeReliefDao.updateVIdeoResourBo(entityBo);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    @Override
    public CutPageBean<IntegrationEntity> Integration(IntegrationEntityBO integrationEntityBO) {
        String dataBase = this.SearchDirection(integrationEntityBO.getType());
        integrationEntityBO.setDatabase(dataBase);
        integrationEntityBO.setStart(integrationEntityBO.page, integrationEntityBO.pageSize);
        String code = CommonConvertUtils.sqllistor("行业分类代码", integrationEntityBO.getCodeList());
        integrationEntityBO.setCode(code);
        integrationEntityBO.setTheUpdateDate(integrationEntityBO.getUpdateDate());
        //处理初级检索SQL
        String primarySearchSql = this.handlePrimarySearch(integrationEntityBO.getSearchType(), integrationEntityBO.getSearchValue());
        integrationEntityBO.setPrimarySearchSql(primarySearchSql);
        //处理高级检索List
        String advSearchSql = this.handleAdvSearchList(integrationEntityBO.getAdvSearchList());
        integrationEntityBO.setAdvSearchSql(advSearchSql);
        CutPageBean<IntegrationEntity> cutPage = new CutPageBean<>();
        List<IntegrationEntity> list = indexDao.Integration(integrationEntityBO);
        //处理时间格式
        if (!list.isEmpty()) {
            list.forEach(entity -> {
                String formatTime = this.handleTimeFormat(entity.getPublishDate());
                entity.setPublishDate(formatTime);
            });
        }
        Long count = indexDao.GetCount(integrationEntityBO);
        Integer counter = count.intValue();

        cutPage.initCutPage(counter, integrationEntityBO.pageSize, list);
        return cutPage;
    }


    /**
     * 处理初级检索集合
     *
     * @param
     * @return
     */
    private String handlePrimarySearch(String searchType, String searchValue) {
        if (!StringUtils.hasLength(searchValue)) {
            return null;
        }
        if ("题名".equals(searchType)) {
            return searchType + "% '" + searchValue + "'";
        } else if ("作者".equals(searchType)) {
            return searchType + "= '" + searchValue + "*'";
        } else if ("机构".equals(searchType)) {
            return searchType + "= '" + searchValue + "*'";
        } else {
            return searchType + "= '*" + searchValue + "'";
        }

    }

    /**
     * 处理高级检索集合
     *
     * @param AdvSearchList
     * @return
     */
    private String handleAdvSearchList(List<Map<String, String>> AdvSearchList) {

        if (CollectionUtils.isEmpty(AdvSearchList))
            return null;
        StringBuffer bf = new StringBuffer("(");
        for (int i = 0; i < AdvSearchList.size(); i++) {
            String key = AdvSearchList.get(i).get("key");
            String value = AdvSearchList.get(i).get("value");
            String logic = "";
            if (i < AdvSearchList.size() - 1) {
                logic = AdvSearchList.get(i + 1).get("logic");
            }
            //如果搜索词和搜索选项为空直接进行下一次循环
            if (!StringUtils.hasLength(key) || !StringUtils.hasLength(value)) {
                continue;
            }
            String symbol = this.choiceSymbol(key);
//                bf.append(key).append("='*").append(value).append("'");
            bf.append(key).append(symbol).append(value).append("'");
            //拼and和or
            if (StringUtils.hasLength(logic)) {
                bf.append(" ").append(logic).append(" ");
            }
        }
        if (bf.length() == 0) {
            return null;
        }
        String returnStr = bf + ")";
        //排除空货号的情况
        if ("()".equals(returnStr)) {
            returnStr = "";
        }
        //排除(题名 = 'xxx' or )和(题名 = 'xxx' and )  的情况
        if (returnStr.endsWith("or )")) {
            returnStr = returnStr.replace("or", "");
        } else if (returnStr.endsWith("and )")) {
            returnStr = returnStr.replace("and", "");
        }
        return returnStr;
    }

    /**
     * 不同的检索词使用不同的语法
     *
     * @param searchType
     * @return
     */
    public String choiceSymbol(String searchType) {
        if ("篇名".equals(searchType) || "题名".equals(searchType)) {
            return " = '";
        } else if ("作者".equals(searchType) || "主题".equals(searchType)) {
            return " % '";
        } else {
            return " = '*";
        }
    }

    /**
     * 页面检索方向
     *
     * @param type
     * @return
     */
    private String SearchDirection(String type) {
        if (!StringUtils.hasLength(type)) {
            return null;
        }
        if ("0".equals(type)) {
            return "应急管理文献";
        } else if ("1".equals(type)) {
            return "MYDXTP";
        } else if ("2".equals(type)) {
            return "MYDXSP";
        } else {
            return null;
        }
    }

    /**
     * 处理时间格式  将其他格式设置为  yyyy-MM-dd
     *
     * @param time
     * @return
     */
    public String handleTimeFormat(String time) {
        String formatTime = "";
        if (StringUtils.hasLength(time)) {
            String format = "yyyy-MM-dd";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            try {
                Date parseTime = simpleDateFormat.parse(time);
                formatTime = simpleDateFormat.format(parseTime);
            } catch (ParseException e) {
//                e.printStackTrace();
                return time;
            }
        }
        return formatTime;
    }

    @Override
    public void AddFrequency(AddFrequencyBo addFrequencyBo) {
        String id = addFrequencyBo.getId();
        if (id == null || "".equals(id)) {//沒有ID
            indexDao.AddFrequency1(addFrequencyBo);
        } else {//有ID
            indexDao.AddFrequency(addFrequencyBo);
        }


       /* Boolean strResult = id.matches("-?[0-9]+.?[0-9]*");
        if(strResult == true) {
            indexDao.AddFrequency(addFrequencyBo);
        }else {
            indexDao.AddFrequency1(addFrequencyBo);
        }*/
    }

    @Override
    public void BrowseFrequency(AddFrequencyBo addFrequencyBo) {
        String str = addFrequencyBo.getId();
        Boolean strResult = str.matches("-?[0-9]+.?[0-9]*");
        if (strResult == true) {
            indexDao.BrowseFrequency(addFrequencyBo);
        }
    }

    @Override
    public CutPageBean<TotalSearchEntityBo> totalSearch(TotalSearchEntityBo totalSearchEntityBo) {
        // 这里我们首先拿到了
        //select * from datasouce where
        totalSearchEntityBo.setStart(totalSearchEntityBo.page, totalSearchEntityBo.pageSize);
        String code ="";
        String codeTwo ="";
        if (totalSearchEntityBo.getCodeList()!=null &&totalSearchEntityBo.getCodeList().length>0){
             code = CommonConvertUtils.sqllistor("行业分类代码", totalSearchEntityBo.getCodeList());
             codeTwo = CommonConvertUtils.sqllistor("期刊标识码", totalSearchEntityBo.getCodeList());
        }
        String primarySearch ="";
        if(code!=null && code!=""){
             primarySearch = code+"OR"+codeTwo;
        }
        totalSearchEntityBo.setPrimarySearchSql(primarySearch);
        String condition = totalSeachPrimary(totalSearchEntityBo.getSearchType(), totalSearchEntityBo.getSearchValue());
        totalSearchEntityBo.setAdvSearchSql(condition);
        // 然后拿到searchType
        List<TotalSearchEntityBo> result = indexDao.totalSearch(totalSearchEntityBo);
        if (!result.isEmpty()) {
            for (TotalSearchEntityBo total : result) {
                String timeFormat = handleTimeFormat(total.getPublishDate());
                total.setPublishDate(timeFormat);
            }
        }
        Long count = indexDao.GetTotalSearchCount(totalSearchEntityBo);
        Integer counter = count.intValue();
        CutPageBean<TotalSearchEntityBo> cutPage = new CutPageBean<>();
        cutPage.initCutPage(counter, totalSearchEntityBo.pageSize, result);
        return cutPage;
    }


    /**
     * 处理初级检索集合
     *
     * @param
     * @return
     */
    private String totalSeachPrimary(String searchType, String searchValue) {
        if (!StringUtils.hasLength(searchValue)) {
            return "";
        }
        if ("题名".equals(searchType)) {
            return searchType + "% '" + searchValue + "'";
        } else if ("作者".equals(searchType)) {
            return searchType + "= '" + searchValue +"'";
        } else if ("机构".equals(searchType)) {
            return searchType + "= '" + searchValue + "*'";
        } else {
            return searchType + "= '*" + searchValue + "'";
        }

    }

}
